# -*- coding: utf8 -*-

import urllib2
from django.utils import simplejson
from puppy.model import Query, Response, Item
from puppy.service.Config import *

def search(query):
  """Search function for Yahoo! BOSS Search.
  
  Parameters:
  
  * query (puppy.model.OpenSearch.Query)
  
  Returns:
  
  * puppy.model.OpenSearch.Response
  
  Raises:
  
  * urllib2.URLError
  
  """
  
  def parse_yahoo_json(site, query, results):
    """Create a OpenSearch Response from Yahoo! BOSS results.
    
    Yahoo!'s search API returns results in JSON format. This function simply loads the JSON into memory and creates an equivalent representation that is OpenSearch compliant.
    
    Parameters:
    
    * site (str): search engine name
    * query (str): query search terms (n.b. not a OpenSearch Query object)
    * results (dict): results from service
    
    Returns:
    
    * OpenSearch.Response
    
    """
    response = Response()
    response.title = "{0}: {1}".format(site, query)
    response.link = results['link']
    response.description = "Search results for '{0}' at {1}".format(query, site)
    response.total_results = results['totalhits']
    response.start_index = results['start']
    response.items_per_page = results['count']
    response.query = query
    for result in results['resultset_web']:
      item = Item()
      item.title = result['title']
      item.link = result['url']
      item.description = result['abstract']
      response.items.append(item)
    return response
  
   
  pos = 1
  url = "http://boss.yahooapis.com/ysearch/web/v1/{0}?appid={1}&format=json&style=raw&filter=-porn-hate&start={2}".format(urllib2.quote(query.search_terms), YAHOO_API_KEY, str(pos))
  results = ''
  try:
    response = urllib2.urlopen(url)
    results = simplejson.load(response)
    results['ysearchresponse'].setdefault(u'link', url)
    return parse_yahoo_json('Yahoo!', query.search_terms, results['ysearchresponse'])
  except urllib2.URLError, e:
    print "Error in SearchService: Yahoo search failed", e
